<script> export default { name: 'common:user' } </script>
<template>
  <el-container>


   <el-container ref="printMain">
    <el-header class="mine-el-header">
      <div class="panel-container">
        <!--列表操作-->
        <div class="left-panel">
          <el-button
            icon="el-icon-plus"
            v-auth="['common:user:save']"
            type="primary"
            @click="add"
          >新增</el-button>

          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            v-auth="['common:user:delete']"
            :disabled="selection.length==0"
            @click="batchDel"
          >删除</el-button>

          <ma-import
            :auth="['common:user:import']"
            :upload-api="commonUser.importExcel"
            :download-tpl-api="commonUser.downloadTemplate"
            @success="handleSuccess()"
          />

          <el-button icon="el-icon-download" v-auth="['common:user:export']" @click="exportExcel">导出</el-button>
        </div>
        <div class="right-panel">
          <div class="right-panel-search">

            <el-input v-model="queryParams.id" placeholder="请输入用户id" clearable />

            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button type="primary" icon="el-icon-search" @click="handlerSearch"></el-button>
            </el-tooltip>

            <el-tooltip class="item" effect="dark" content="清空条件" placement="top">
              <el-button icon="el-icon-refresh" @click="resetSearch"></el-button>
            </el-tooltip>

            <el-button type="text" @click="toggleFilterPanel">
              {{ povpoerShow ? '关闭更多筛选' : '显示更多筛选'}}
              <el-icon><el-icon-arrow-down v-if="povpoerShow" /><el-icon-arrow-up v-else /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      <!--列表筛选-->
      <el-card class="filter-panel" shadow="never">
        <el-form label-width="80px" :inline="true">

          <el-form-item label="用户账号" prop="account">
            <el-input v-model="queryParams.account" placeholder="请输入用户账号" clearable />
          </el-form-item>

          <el-form-item label="用户密码" prop="pwd">
            <el-input v-model="queryParams.pwd" placeholder="请输入用户密码" clearable />
          </el-form-item>

          <el-form-item label="身份证号码" prop="card_id">
            <el-input v-model="queryParams.card_id" placeholder="请输入身份证号码" clearable />
          </el-form-item>

          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="queryParams.nickname" placeholder="请输入用户昵称" clearable />
          </el-form-item>

          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable />
          </el-form-item>

          <el-form-item label="添加时间" prop="add_time">
            <el-input v-model="queryParams.add_time" placeholder="请输入添加时间" clearable />
          </el-form-item>

          <el-form-item label="用户余额" prop="now_money">
            <el-input v-model="queryParams.now_money" placeholder="请输入用户余额" clearable />
          </el-form-item>

          <el-form-item label="佣金金额" prop="brokerage_price">
            <el-input v-model="queryParams.brokerage_price" placeholder="请输入佣金金额" clearable />
          </el-form-item>

          <el-form-item label="用户剩余积分" prop="integral">
            <el-input v-model="queryParams.integral" placeholder="请输入用户剩余积分" clearable />
          </el-form-item>

          <el-form-item label="会员经验" prop="exp">
            <el-input v-model="queryParams.exp" placeholder="请输入会员经验" clearable />
          </el-form-item>

          <el-form-item label="连续签到天数" prop="sign_num">
            <el-input v-model="queryParams.sign_num" placeholder="请输入连续签到天数" clearable />
          </el-form-item>

          <el-form-item label="分销等级" prop="agent_level">
            <el-input v-model="queryParams.agent_level" placeholder="请输入分销等级" clearable />
          </el-form-item>

          <el-form-item label="是否有推广资格" prop="spread_open">
            <el-input v-model="queryParams.spread_open" placeholder="请输入是否有推广资格" clearable />
          </el-form-item>

          <el-form-item label="推广员关联时间" prop="spread_time">
            <el-input v-model="queryParams.spread_time" placeholder="请输入推广员关联时间" clearable />
          </el-form-item>

          <el-form-item label="用户类型，shop,erp,crm" prop="user_type">
            <el-select v-model="queryParams.user_type" placeholder="请选择用户类型，shop,erp,crm" clearable>
              <el-option
                v-for='(item, index) in dictData.user_type'
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="事业部/代理/员工结束时间" prop="division_end_time">
            <el-input v-model="queryParams.division_end_time" placeholder="请输入事业部/代理/员工结束时间" clearable />
          </el-form-item>

          <el-form-item label="代理商邀请码" prop="division_invite">
            <el-input v-model="queryParams.division_invite" placeholder="请输入代理商邀请码" clearable />
          </el-form-item>

          <el-form-item label="创建时间" prop="created_at">
            <el-date-picker
              v-model="queryParams.created_at" placeholder="请选择创建时间时间"
              type="datetimerange"  start-placeholder="起始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

        </el-form>
      </el-card>
    </el-header>
    <!--表格列表-->
    <el-main class="nopadding">
      <maTable
        ref="table"
        :api="api"
        :showRecycle="true"
        row-key="id"
        :hidePagination="false"
        @selection-change="selectionChange"
        @switch-data="switchData"
        stripe
        remoteSort
        @row-contextmenu="rowContextmenu"
      >
        <el-table-column type="selection" width="50"></el-table-column>

          <el-table-column label="用户id" prop="id"  />

        <el-table-column label="用户头像" prop="avatar" >
          <template #default="scope">
           <div :style="{width: proxy.$CONFIG.INDEX_IMAGE.WIDTH,height: proxy.$CONFIG.INDEX_IMAGE.HEIGHT}">
          	<el-image
          		:src="scope.row.avatar"
          		fit="cover"
          		:preview-src-list="[scope.row.avatar]"
          		preview-teleported
          		hide-on-click-modal
          	/>
           </div>
          </template>
        </el-table-column>

          <el-table-column label="用户账号" prop="account"  />

<!--          <el-table-column label="用户密码" prop="pwd"  />-->

          <el-table-column label="真实姓名" prop="real_name"  />

          <el-table-column label="身份证号码" prop="card_id"  />

          <el-table-column label="用户昵称" prop="nickname"  />

          <el-table-column label="手机号码" prop="phone"  />

          <el-table-column label="添加时间" prop="add_time"  />

          <el-table-column label="用户余额" prop="now_money"  />

          <el-table-column label="佣金金额" prop="brokerage_price"  />

          <el-table-column label="用户剩余积分" prop="integral"  />

          <el-table-column label="会员经验" prop="exp"  />

          <el-table-column label="连续签到天数" prop="sign_num"  />

          <el-table-column label="分销等级" prop="agent_level"  />

          <el-table-column label="是否有推广资格" prop="spread_open"  />

          <el-table-column label="推广员关联时间" prop="spread_time"  />

          <el-table-column label="详细地址" prop="address"  />

          <el-table-column label="用户类型，shop,erp,crm" prop="user_type" >
            <template #default="scope">
              <ma-dict-tag :options="dictData.user_type" :value="scope.row.user_type" />
            </template>
          </el-table-column>

          <el-table-column label="事业部/代理/员工结束时间" prop="division_end_time"  />

          <el-table-column label="代理商邀请码" prop="division_invite"  />

          <el-table-column label="创建时间" prop="created_at" width="100"  />

        <!-- 正常数据操作按钮 -->
        <el-table-column label="操作" fixed="right" align="right" width="130" v-if="!isRecycle">
          <template #default="scope">

            <el-button
              type="text"
              @click="tableEdit(scope.row, scope.$index)"
              v-auth="['common:user:update']"
            >编辑</el-button>

            <el-button
              type="text"
              @click="deletes(scope.row.id)"
              v-auth="['common:user:delete']"
            >删除</el-button>

          </template>
        </el-table-column>

        <!-- 回收站操作按钮 -->
        <el-table-column label="操作" fixed="right" align="right" width="130" v-else>
          <template #default="scope">

            <el-button
              type="text"
              v-auth="['common:user:recovery']"
              @click="recovery(scope.row.id)"
            >恢复</el-button>

            <el-button
              type="text"
              v-auth="['common:user:realDelete']"
              @click="deletes(scope.row.id)"
            >删除</el-button>

          </template>
        </el-table-column>

      </maTable>
    </el-main>

    <sc-contextmenu ref="contextmenu"  @command="handleCommand" @visible-change="visibleChange">
    	<sc-contextmenu-item command="edit" title="编辑"  suffix="Alt+←" icon="el-icon-edit"></sc-contextmenu-item>
    	<sc-contextmenu-item command="delete" title="删除" suffix="Ctrl+R" icon="el-icon-delete"></sc-contextmenu-item>
    </sc-contextmenu>

   </el-container>
  </el-container>

  <!--操作页面-->
  <save-dialog v-if="dialog.save" ref="saveRef" @success="handleSuccess" @closed="dialog.save=false" />

</template>
<script setup>
  import { ref, reactive, onMounted, nextTick,getCurrentInstance } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import commonUser from '@/api/apis/common/commonUser'
  import tool from '@/utils/tool'
  import systemDict from '@/api/apis/system/dataDict'
  import scContextmenu from '@/components/scContextmenu'
  import scContextmenuItem from '@/components/scContextmenu/item'
  import saveDialog from './save.vue'

  const router = useRouter();
  const { proxy } = getCurrentInstance();
  const table = ref(null)
  const saveRef = ref(null)
  const povpoerShow = ref(false)
  const isRecycle = ref(false)
  const dateRange = ref()
  const selection = ref([])
  const default_tabs_key = ref('-1')
  const contextmenu = ref(null)
  const rowdata = reactive({row:{}})

  const dialog = reactive({ save: false })
  const api = reactive({ list: commonUser.getList, recycleList: commonUser.getRecycleList })
  const queryParams = reactive({
    id: '',
    account: '',
    pwd: '',
    card_id: '',
    nickname: '',
    phone: '',
    add_time: '',
    now_money: '',
    brokerage_price: '',
    integral: '',
    exp: '',
    sign_num: '',
    agent_level: '',
    spread_open: '',
    spread_time: '',
    user_type: '',
    division_end_time: '',
    division_invite: '',
    created_at: '',

  })
  const dictData = reactive({
    user_type: [],

  })

  onMounted(async () => {
    await getDictData()
  })

  //添加
  const add = async () => {
    dialog.save = true
    await nextTick()
    saveRef.value.open()
  }

   // 标签页查询
    const handleTabsClick = (name) => {

    }

  //编辑
  const tableEdit = async (row) => {
    dialog.save = true
    await nextTick()
    saveRef.value.open('edit')
    saveRef.value.setData(row)
  }

  //查看
  const tableShow = async (row) => {
    dialog.save = true
    await nextTick()
    saveRef.value.open('show')
    saveRef.value.setData(row)
  }

  //批量删除
  const batchDel = async () =>{
    await ElMessageBox.confirm(`确定删除选中的 ${selection.value.length} 项吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(async () => {
      let ids = []
      selection.value.map(item => ids.push(item.id))
      let res = isRecycle.value ? await commonUser.realDeletes(ids.join(',')) : await commonUser.deletes(ids.join(','))
      table.value.upData(queryParams)
      ElMessage.success(res.message)
    }).catch(()=>{})
  }

  // 单个删除
  const deletes = async (id) => {
    await ElMessageBox.confirm(`确定删除该数据吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(async () => {
      let res = isRecycle.value ? await commonUser.realDeletes(id) : await commonUser.deletes(id)
      table.value.upData(queryParams)
      ElMessage.success(res.message)
    }).catch(()=>{})
  }

  // 恢复数据
  const recovery = (id) => {
    commonUser.recoverys(id).then(res => {
      ElMessage.success(res.message)
      table.value.upData(queryParams)
    })
  }

  // 右键菜单
  const rowContextmenu = (row,column,event) => {

  	rowdata.row = row
  	table.value.setCurrentRow(row);
  	contextmenu.value.openMenu(event)
  }

  const handleCommand = (command) => {
  	if (command == 'edit') {
  		tableEdit(rowdata.row)
  	}
  	if (command == 'delete') {
  		deletes(rowdata.row.id)
  	}
  }

  const visibleChange = (visible) => {
  	if (!visible) {
  	}
  }

  //表格选择后回调事件
  const selectionChange = (items) => {
    selection.value = items
  }

  const toggleFilterPanel = () => {
    povpoerShow.value = ! povpoerShow.value
    document.querySelector('.filter-panel').style.display = povpoerShow.value ? 'block' : 'none'
  }

  //搜索
  const handlerSearch = () => {
    table.value.upData(queryParams)
  }

  // 切换数据类型回调
  const switchData = () => {
    isRecycle.value = ! isRecycle.value
  }

  // 重置搜索
  const resetSearch = () => {
    for (let k in queryParams) {

        queryParams[k] = undefined
    }
    table.value.upData(queryParams)
  }

  // 更新
  const handleSuccess = () =>{
    table.value.upData(queryParams)
  }

  // 获取字典数据
  const getDictData = () => {
    systemDict.getDict('user_type').then(res => {
      dictData.user_type = res.data
    })

  }

  // 修改单个数据
  	 const updateSingle = (id, editField,editValue) => {
       	let data = {[editField]: editValue};
       	commonUser.updateSingle(id, data).then(() => {
       		ElMessage.success('修改成功')
       	})
       }


  const exportExcel = () => {
    ElMessage.info('正在处理数据...')
    commonUser.exportExcel(queryParams).then( res => {
      tool.download(res)
    }).catch( e => { console.log(e) } )
  }

  const numberOperation = (newValue, id, numberName) => {
    commonUser.numberOperation({ id, numberName, numberValue: newValue }).then( res => {
      res.success && ElMessage.success(res.message)
    }).catch( e => { console.log(e) } )
  }

  const switchStatus = (statusValue, id, statusName) => {
    commonUser.changeStatus({ id, statusName, statusValue }).then( res => {
      res.success && ElMessage.success(res.message)
    }).catch( e => { console.log(e) } )
  }

</script>
